package com.fyb.bloomFilter.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fyb.bloomFilter.cache.RedisCacheService;
import com.fyb.bloomFilter.mapper.UserMapper;
import com.fyb.bloomFilter.model.UserEntity;
import com.fyb.bloomFilter.service.BloomFilterService;
import com.fyb.bloomFilter.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BloomFilterService bloomFilterService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RedisCacheService redisCacheService;

    @Override
    public UserEntity getUserById(Long id) {
        // Step 1: 使用 Bloom Filter 检查用户 ID 是否可能在数据库中
        if (!bloomFilterService.contains(id)) {
            // 如果 Bloom Filter 显示它不存在，则直接返回 null
            return null;
        }

        // Step 2: 首先检查 Redis 缓存
        UserEntity user = null;
        Object cachedObject = redisCacheService.getUserFromCache(id);
        if (cachedObject instanceof LinkedHashMap) {
            // 将 LinkedHashMap 转换为 UserEntity
            user = objectMapper.convertValue(cachedObject, UserEntity.class);
        }
        if (user != null) {
            // 如果在缓存中找到，则返回缓存的用户
            return user;
        }

        // Step 3: 如果不在缓存中，则查询数据库
        user = userMapper.getUserById(id);

        // Step 4: 如果在数据库中找到 user，则添加到 Redis 缓存
        if (user != null) {
            redisCacheService.putUserToCache(user);
        }

        return user;
    }
}